package com.blue.Impl.ai;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.blue.common.constant.CommonConstant;
import com.blue.common.entity.LoginUserInfo;
import com.blue.common.utils.ConvertUtils;
import com.blue.common.utils.ThreadLocalUtils;
import com.blue.dto.ai.ChatHistoryDTO;
import com.blue.dto.ai.ChatHistoryDetailDTO;
import com.blue.mapper.ai.ChatHistoryMapper;
import com.blue.po.ai.ChatHistoryDetailPO;
import com.blue.po.ai.ChatHistoryPO;
import com.blue.service.ai.IChatHistoryDetailService;
import com.blue.service.ai.IChatHistoryService;
import com.blue.vo.ai.ChatHistoryDetailVO;
import com.blue.vo.ai.ChatHistoryVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;


@Service
public class ChatHistoryServiceImpl extends ServiceImpl<ChatHistoryMapper, ChatHistoryPO> implements IChatHistoryService {

    @Autowired
    private IChatHistoryDetailService chatHistoryDetailService;

    @Override
    @Transactional
    public void add(ChatHistoryDTO requestDTO) {
        LoginUserInfo loginUserInfo = ThreadLocalUtils.getLoginUserInfo();
        String userId = loginUserInfo.getUserId();
        long count = this.count(new LambdaQueryWrapper<ChatHistoryPO>()
                .eq(ChatHistoryPO::getCreatorId, userId)
                .eq(ChatHistoryPO::getIsFlag, CommonConstant.YES));
        //每个用户最多保留5条记录
        if (count >= 10) {
            List<String> ids = this.list(new LambdaQueryWrapper<ChatHistoryPO>()
                            .select(ChatHistoryPO::getId)
                            .eq(ChatHistoryPO::getIsFlag, CommonConstant.YES)
                            .orderByAsc(ChatHistoryPO::getCreateTime)
                            .last("limit " + (count - 9)))
                    .stream()
                    .map(ChatHistoryPO::getId)
                    .toList();
            this.update(new LambdaUpdateWrapper<ChatHistoryPO>()
                    .set(ChatHistoryPO::getIsFlag, CommonConstant.NO)
                    .in(ChatHistoryPO::getId,ids));
        }
        ChatHistoryPO ChatHistoryPO = ConvertUtils.convert(ChatHistoryPO.class, requestDTO);
        this.save(ChatHistoryPO);
        List<ChatHistoryDetailDTO> chatHistoryDetailDTOS = requestDTO.getChatHistoryDetailDTOS();
        if (!CollectionUtils.isEmpty(chatHistoryDetailDTOS)) {
            List<ChatHistoryDetailPO> chatHistoryDetailPOS = ConvertUtils.convertList(ChatHistoryDetailPO.class, chatHistoryDetailDTOS);
            chatHistoryDetailPOS.forEach(item -> item.setHistoryId(ChatHistoryPO.getId()));
            chatHistoryDetailService.saveBatch(chatHistoryDetailPOS);
        }
    }
}
